package com.shsxt.service;



import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.ZhimaCustomerCertificationInitializeRequest;
import com.alipay.api.response.ZhimaCustomerCertificationInitializeResponse;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.shsxt.controller.Test;
import com.shsxt.controller.YunTongXun;
import com.shsxt.dao.AuntDao;
import com.shsxt.dao.ControllDao;
import com.shsxt.dao.CouponDao;
import com.shsxt.dao.OrderDao;
import com.shsxt.dao.WodeDao;
import com.shsxt.dao.YuyueDao;
import com.shsxt.model.Address;
import com.shsxt.model.COrder;
import com.shsxt.model.CheckNumber;
import com.shsxt.model.Coupon;
import com.shsxt.model.CreditsDetail;
import com.shsxt.model.DOrder;
import com.shsxt.model.Invite;
import com.shsxt.model.JOrder;
import com.shsxt.model.KOrder;
import com.shsxt.model.Location;
import com.shsxt.model.Notified;
import com.shsxt.model.ROrder;
import com.shsxt.model.SOrder;
import com.shsxt.model.SignIn;
import com.shsxt.model.UserInfo;
import com.shsxt.model.WithdrawDetail;
import com.shsxt.util.Daojishi;
import com.shsxt.util.OSSClientUtil;
import com.shsxt.util.Push;
import com.shsxt.util.my.MyParam;
import com.shsxt.util.my.MyUtil;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;

@Service
public class WodeService {
	@Autowired
	public  WodeDao wodeDao;
	@Autowired
	public ControllService controllService;
	@Autowired
	public YuyueDao yuyueDao;
	@Autowired
	public CouponDao couponDao;
	@Autowired
	public OrderDao orderDao;
	@Autowired
	public AuntDao auntDao;
	@Autowired
	public WodeService wodeService;
	@Autowired
	public ControllDao controllDao;
	@Autowired
	private OSSClientUtil ossClient;
	
	//--------------------------------------------------------------------------------------------
	  //点击我的
		public Map<String,Object> findWodeMessages(String phoneNumber) throws ParseException {
			
			
			Map<String,Object> map=new HashMap<String,Object>();

				UserInfo user=wodeDao.findUserByPhone(phoneNumber);
				String signin="今天未签到";
				SignIn sign=wodeDao.findSignByPhone(phoneNumber);
				//新用户创建签到 
				if(sign==null){
					wodeDao.createSign(phoneNumber);
				}
				sign=wodeDao.findSignByPhone(phoneNumber);
		        Date d= new Date();
		        //比较时间差是否为0
				int a=daysOfTwo(sign.getSignTime(),d);
				if(a==0){
					signin="今天已签到";
				}
				map.put("0", user.getHeadPortrait());
				map.put("1", user.getPetName());
				map.put("2", user.getUserType());
				map.put("3", signin);
				map.put("4", user.getNotified());
				return map;
			
		}
	//点击头像  ：个人中心
		public Map<String,Object> findMessages(String phoneNumber,HttpServletRequest request) throws ParseException {
			
			UserInfo user=wodeDao.findUserByPhone(phoneNumber);
			Map<String,Object> map=new HashMap<String,Object>();
	        if(user!=null){
	        	SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd");        
		        String birthday= myFmt.format(user.getBirthday());
		        map.put("0", user.getHeadPortrait());
				map.put("1", user.getPetName());
				map.put("2", user.getUserType());
				map.put("3", user.getSex());
				map.put("4", birthday);
				map.put("5", phoneNumber);
				map.put("6", user.getNotified());
	        }else{
	        	map.put("0", "失败");
	        }
	        

			return map;
		}
		
	 //点击头像  ：个人中心:保存(除了头像之外的信息)
		public Map<String, Object> updateMessages(String petName,  String sex, String birthday, String phoneNumber) throws ParseException  {
			
			Map<String, Object> param = new HashMap<String,Object>();
			//原来性别是不是为空
			UserInfo user=wodeDao.findUserByPhone(phoneNumber);
			String sexDefault=user.getSex();
			param.put("sexDefault",sexDefault);
			param.put("petName",petName);
			param.put("sex",sex);
			SimpleDateFormat sdf =new SimpleDateFormat( "yyyy-MM-dd" );
			Date d = sdf.parse( birthday );
		
			param.put("birthdayDefault", sdf.format(user.getBirthday()));
			param.put("birthday",d);
			param.put("phoneNumber",phoneNumber);
			int a=wodeDao.updateMessages(param);
			Map<String, Object> map = new HashMap<String,Object>();
			if(a==1){
				map.put("0", "成功");
			}else{
				map.put("0", "失败");
			}
			
			return map;
		}	
		
	 //返回储存头像地址的文件夹,并将完路径的头像地址存到数据库
		public Map<String, Object> updateHeadStr(HttpSession session,String phoneNumber,HttpServletRequest request,
				HttpServletResponse response) throws IllegalStateException, IOException, ParseException {
				
			Map<String,Object> map=new HashMap<String,Object>();
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
						request.getSession().getServletContext());
				if (multipartResolver.isMultipart(request)) {
					MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
					//获取所有文件

					Iterator<String> iter = multiRequest.getFileNames();

					while (iter.hasNext()) {
						//获取当前文件
						MultipartFile file = multiRequest.getFile((String) iter.next());
						   CommonsMultipartFile cf= (CommonsMultipartFile)file; 
					        DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
					        File f = fi.getStoreLocation();
						long   size =   f.length(); //   大小   bytes 
						System.err.println("size"+size);
						System.err.println( file.getOriginalFilename());
						if(size>1024000){
							map.put("0", "图片大于1M");
							return map;
						//图片大于一兆
						}
						String fileName = file.getOriginalFilename();//储存地址
						System.err.println(fileName);
						if(fileName.substring(fileName.length()-3, fileName.length()).equals("peg")){
							//给图片命名手机好+时间戳
							fileName=phoneNumber+System.currentTimeMillis()+fileName.substring(fileName.length()-5, fileName.length());
						}else{
							fileName=phoneNumber+System.currentTimeMillis()+fileName.substring(fileName.length()-4, fileName.length());
						}
						System.err.println("filename:"+fileName);
						if (fileName != null&&!fileName.equals("")) {//文件内容不为空
							String path1 = session.getServletContext().getRealPath("images")+File.separator;// 储存地址+文件名 
							String path = path1 +fileName;//创建文件
							File localFile = new File(path);
							System.err.println(path);
							deleteHead(phoneNumber,session);
							file.transferTo(localFile);
							Map<String, Object> param = new HashMap<String,Object>();
							param.put("phoneNumber",phoneNumber);
							param.put("fullPath","http://139.196.102.135/cleaning/images/"+fileName);
							int a=wodeDao.updateHeadStr(param);
							if(a==1){
								map.put("0", "成功");
								return map;
							}
							map.put("0", "失败");
							return map;
							
						}else{
							map.put("0", "成功");
							return map;

				        }
					}
				}
				map.put("0", "失败");
				return map;
		}	
		
		  //点击普通用户： 用户经验和等级(经验值等级差多少升级)

	public Map<String,Object> levelMessages(String phoneNumber) throws ParseException {
	
		Map<String,Object> map=new HashMap<String,Object>();
		UserInfo user=wodeDao.findUserByPhone(phoneNumber);
		String level=user.getMemberLevel();
		map.put("0", user.getMemberBalance()+"");
		map.put("1", level);
		map.put("2", "您现在是"+level+"会员,如果想升级会员请购买相应的会员卡。");
		return map;
	}
	//点击签到有奖： 签到奖励积分(签到成功字符串)
	public Map<String,Object> signInMessages(String phoneNumber) throws ParseException {
		
		Map<String,Object> map=new HashMap<String,Object>();
		Map<String, Object> param = new HashMap<String,Object>();
		Map<String, Object> creditsDetail = new HashMap<String,Object>();
		param.put("phoneNumber",phoneNumber);
		creditsDetail.put("type", "每日签到");
		creditsDetail.put("phoneNumber", phoneNumber);
		//获取这个用户的签到信息
		SignIn sign=wodeDao.findSignByPhone(phoneNumber);
		//如果从来没有签到过就创建并签到一天
		if(sign==null){
			wodeDao.createSign(phoneNumber);
			map.put("0", "签到成功");
			map.put("1", "您已签到1天，再连续签到6天可额外获得30积分！");
			creditsDetail.put("upCredits", 3);
			wodeDao.createCreditsDetail(creditsDetail);
			exchangeCredits(phoneNumber);
			return map;
		}
		param.put("credits",sign.getCredits()+3);
		wodeDao.updateCredits(param);
        Date d= new Date();
        //比较时间差a来进行1连续签到0已签到--重新签到
		int a=daysOfTwo(sign.getSignTime(),d);
		if(a==1){
			creditsDetail.put("upCredits", 3);
			wodeDao.createCreditsDetail(creditsDetail);
			if(sign.getSignCount()!=6){
				map.put("0", "签到成功");
				map.put("1", "您已经签到"+(sign.getSignCount()+1)+"天,再连续签到"+(6-sign.getSignCount())+"天可额外获得30积分！");
				param.put("signCount",sign.getSignCount()+1);
				wodeDao.updateSignCount(param);
			}else{
				//签到满7天
				map.put("0", "签到成功");
				map.put("1", "您已经签满7天，额外送30积分，请注意查收！");
				param.put("credits",sign.getCredits()+33);
				wodeDao.updateCredits(param);
				param.put("signCount",0);
				wodeDao.updateSignCount(param);
				creditsDetail.put("upCredits", 15);
				wodeDao.createCreditsDetail(creditsDetail);
			}
		}else if(a==0){
			map.put("0", "您已签到");
			map.put("1", "您已经签到"+(sign.getSignCount())+"天,再连续签到"+(7-sign.getSignCount())+"天可额外获得30积分！");
			param.put("credits",sign.getCredits());
			wodeDao.updateCredits(param);
		}else{
			//很早以前签到
			creditsDetail.put("upCredits", 3);
			wodeDao.createCreditsDetail(creditsDetail);
			map.put("0", "签到成功");
			map.put("1", "您已签到1天，再连续签到6天可额外获得30积分！");
			param.put("signCount",1);
			wodeDao.updateSignCount(param);
		}
		param.put("signTime",d);
		wodeDao.updateSignTime(param);
		exchangeCredits(phoneNumber);
		return map;
	}
	
	//邀请有礼(url)
	public Map<String,Object> invite(String phoneNumber) throws ParseException {
		
		SignIn sign=wodeDao.findSignByPhone(phoneNumber);
		//该用户有无积分记录
		if(sign==null){
			wodeDao.createSign(phoneNumber);
			sign=wodeDao.findSignByPhone(phoneNumber);
		}
		Map<String, Object> param = new HashMap<String,Object>();
		//加10积分
		param.put("phoneNumber",phoneNumber);
		param.put("credits",sign.getCredits()+10);
		param.put("type","邀请有礼");
		param.put("upCredits",10);

		wodeDao.updateCredits(param);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("0", "http://139.196.102.135/view/share/share.html");
		Date d= new Date();
		Invite invite=wodeDao.findInviteByPhone(phoneNumber);
		//这个用户曾今邀请过人没，创建记录
		if(null==invite){
			wodeDao.createInviteByPhone(phoneNumber);
			wodeDao.insertCreditsDetail(param);
			map.put("1", "今天已邀请1次");
		}else{
			//上次邀请是今天吗
			int a=daysOfTwo(invite.getTime(),d);
			if(a==0){
				//今天邀请满5次没有
				if(invite.getInviteCount()<5){
					param.put("inviteCount",invite.getInviteCount()+1);
					wodeDao.updateInvite(param);
					wodeDao.insertCreditsDetail(param);
					int b=invite.getInviteCount()+1;
					map.put("1", "今天已邀请"+b+"次");
					
				}else{
					map.put("1","今天邀请次数上限");
					//将已前面已+的10积分还原
					param.put("credits",sign.getCredits());
					wodeDao.updateCredits(param);
				}
				
				//今天第一次邀请
			}else{
				param.put("inviteCount",1);
				wodeDao.updateInvite(param);
				map.put("1","今天已邀请1次");
			}
		}
		exchangeCredits(phoneNumber);
		return map;
	}
	// //我的：地址(此用户所有地址：地址默认手机号)
		public Map<String,Object> addressMessages(String phoneNumber) throws ParseException {
			
			List<Address> addressMessages=new ArrayList<Address>();
			addressMessages=wodeDao.findAddressByPhone(phoneNumber);
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("A", paixuAddress(addressMessages));
			return map;
			
		}
		//我的：地址：添加新地址？手机地址默认
		public Map<String, Object> addAddress(String phoneNumber, String address,String realPhoneNumber, String detailAddress,String tag,String location) throws ParseException {
			
			Map<String, Object> param = new HashMap<String,Object>();
			param.put("phoneNumber",phoneNumber);
			param.put("address",address);
			param.put("tag",tag);
			param.put("realPhoneNumber",realPhoneNumber);
			param.put("location",location);

			param.put("detailAddress",detailAddress);
			param.put("uuid",UUID.randomUUID().toString());
			//新地址是不是要默认
			List<Address> addressMessages=new ArrayList<Address>();
			addressMessages=wodeDao.findAddressByPhone(phoneNumber);
			System.err.println("addressMessages"+addressMessages);
			if(tag.equals("1")){
				//遍历用户的全部地址，如有已默认则设取消
				for(Address a:addressMessages){
					if (a.getTag().equals("1")){
						param.put("uuidT",a.getUuid());
						wodeDao.updateTagAddress(param);
					}
				}
			}else{
				if(addressMessages.size()==0){
					param.put("tag","1");
				}
			}
			
			//添加地址
			int l=wodeDao.addAddress(param);
			Map<String, Object> map = new HashMap<String,Object>();
			if(l!=-1){
				map.put("0", "成功");
			}else{
				map.put("0", "失败");
			}
			return map;
		}
		//我的：地址：编辑地址:保存?手机地址默认
		public Map<String,Object> saveAddress(String uuid,String address,String realPhoneNumber,String detailAddress,String tag,String location) {
			Map<String, Object> param = new HashMap<String,Object>();
			param.put("uuid",uuid);
			param.put("address",address);
			param.put("detailAddress",detailAddress);
			param.put("realPhoneNumber",realPhoneNumber);
			param.put("tag",tag);
			param.put("location",location);
			Address addressOne=wodeDao.findAddressByUuid(uuid);
			String pn=addressOne.getPhoneNumber();
			List<Address> addressMessages=new ArrayList<Address>();
			addressMessages=wodeDao.findAddressByPhone(pn);
				if(tag.equals("1")){
					//遍历用户的全部地址，如有已默认则设取消
					for(Address a:addressMessages){
						if (a.getTag().equals("1")){
							param.put("uuidT",a.getUuid());
							wodeDao.updateTagAddress(param);
						}
					}
				}else{
					if(addressMessages.size()==1){
						param.put("tag","1");
					}
				}
			//修改地址
			int l=wodeDao.updateAddress(param);
			Map<String, Object> map = new HashMap<String,Object>();
				map.put("0", "成功");
			return map;

			
		}
		
		
		//删除地址
		public Map<String, Object> deleteAddress(String uuid) {
			Map<String, Object> map = new HashMap<String,Object>();
			Address addressOne=wodeDao.findAddressByUuid(uuid);
			String pn=addressOne.getPhoneNumber();
			//删除这条
			int l=wodeDao.deleteAddress(uuid);
			//如果删除的是默认  自动拿另一条地址设为默认
			List<Address> addressMessages=new ArrayList<Address>();
			addressMessages=wodeDao.findAddressByPhone(pn);
			if(addressMessages.size()>=1){
				wodeDao.updateTagOne(pn);
			}
				map.put("0","成功");
			return map;
		}

	//--------------------------------------------------------	-------------------------------------
	
	
	public static int daysOfTwo(Date fDate, Date oDate) {

	       Calendar aCalendar = Calendar.getInstance();

	       aCalendar.setTime(fDate);

	       int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);

	       aCalendar.setTime(oDate);

	       int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);

	       return day2 - day1;

	    }
	//获取余额
	public Map<String,Object> memberBalanceMessages(String phoneNumber) {
		UserInfo user=wodeDao.findUserByPhone(phoneNumber);
		Map<String,Object> a=new HashMap<String,Object>();
		a.put("0", user.getMemberBalance()+"");
		return a;
	}
	//获取积分//查询用户的积分明细
	public Map<String,Object> creditsMessages(String phoneNumber) {
		UserInfo user=wodeDao.findUserByPhone(phoneNumber);
		List<CreditsDetail> cd=new ArrayList<CreditsDetail>();
		 cd=wodeDao.findCreditsDetailByPhone(phoneNumber);
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("0", user.getPoints()+"");
		map.put("detail", cd);
		return map;
	}
	//设置：用户反馈?手机号反馈
	public Map<String, Object> addFeedBack(String phoneNumber, String text) {
		Map<String, Object> param = new HashMap<String,Object>();
		param.put("phoneNumber",phoneNumber);
		param.put("text",text);
		Map<String, Object> map = new HashMap<String,Object>();
		if(text==null){
			map.put("0","失败");
			return map;
		}
		int l=wodeDao.addFeedBack(param);
		
		if(l!=-1){
			map.put("0","成功");
		}else{
			map.put("0","失败");
		}
		return map;
	}
	//地址：默认
	public Map<String, Object> defaultAddress(String uuid) {
		Map<String, Object> map=new HashMap<String,Object>();
		Address addressOne=wodeDao.findAddressByUuid(uuid);
		//根据uuid查找电话号码
		String pn=addressOne.getPhoneNumber();
		
		Map<String, Object> param=new HashMap<String,Object>();
		param.put("uuid", uuid);
		param.put("phoneNumber", pn);
		//设为默认
		int l=wodeDao.defaultAddress(uuid);
		//剩下的设为不默认
		int x=wodeDao.defaultAddressrev(param);
		System.err.println(l+"=="+x);
		if(l!=-1&&x!=-1){
			map.put("0","成功");
		}else{
			map.put("0","失败");
		}
		return map;
	}
	//token------------------------------------------------
	public Map<String, Object> detailAddress(String uuid) {
		Address addressOne=wodeDao.findAddressByUuid(uuid);
		Map<String, Object> map=new HashMap<String,Object>();
		map.put("0",addressOne.getAddress());
		map.put("1",addressOne.getDetailAddress());
		map.put("2",addressOne.getRealPhoneNumber());
		map.put("3",addressOne.getTag());
		map.put("4",addressOne.getUuid());
		map.put("5",addressOne.getLocation());

		return map;
	}
	public Map<String, Object> findCoupon(String phoneNumber) {
		Map<String,Object> map=new HashMap<String,Object>();
		List<Coupon>  cp=new ArrayList<Coupon>();
		cp=wodeDao.findCouponByPhone(phoneNumber);
		map.put("coupon", cp);
		return map;
	}
	//------------------------------------------------------
	  public String updateHead(HttpServletRequest request,HttpSession session, String userId) throws Exception{
		    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				//获取所有文件
				Iterator<String> iter = multiRequest.getFileNames();
					//获取当前文件
					MultipartFile file = multiRequest.getFile((String) iter.next());
					String imgUrl ="";	
		    String name = ossClient.uploadImg2Oss(file,userId);
		    if(name.substring(name.length()-4, name.length()).equals("jpeg")){
			    imgUrl ="http://yiyunwangl.oss-cn-hangzhou.aliyuncs.com/cleaning/images/"+userId+name.substring(name.length()-5, name.length());

		    }else{
			    imgUrl ="http://yiyunwangl.oss-cn-hangzhou.aliyuncs.com/cleaning/images/"+userId+name.substring(name.length()-4, name.length());
		    }
		    Map<String,Object> param=new HashMap<String,Object>();
		    param.put("phoneNumber", userId);
		    param.put("fullPath", imgUrl);
		    int l=wodeDao.updateHeadStr(param);//只是本地上传使用的
				if(l==1){
					return "成功";
				}else{
					 return "失败";
				}
		   
				}
				return "失败";
		  }
	  public Map<String, Object> login(String phoneNumber, String type, String number) throws ParseException, APIConnectionException, APIRequestException {
		  UserInfo user=wodeDao.findUserByPhone(phoneNumber);
		  Map<String,Object> param=new HashMap<String,Object>();
			param.put("phoneNumber", phoneNumber);	
			param.put("name", "用户yjj"+((int)(Math.random()*9000)+1000));
			int a=0;
			if(null==user){
				wodeDao.createUser(param);
				registerCoupon(phoneNumber);
				a=1;
			}
			Map<String,Object> map=new HashMap<String,Object>();
			Map<String,Object> duanxin=new HashMap<String,Object>();
			
			duanxin=duanxin(phoneNumber,type,number);
			String newToken= UUID.randomUUID().toString();
			if(duanxin.get("0").equals("成功")){
				if(a==1){
					map.put("0", "成功");
				}else{
					map.put("0", "已注册");
				}
				
				param.put("token", newToken);
				controllDao.updateToken(param);
				
				
				return map;
			}else{
				map.put("0", duanxin.get("0"));
			}
			//验证码错误返回  验证错误信息
			return map;
		}
		//查找验证码
	public Map<String, Object> duanxin(String phoneNumber, String type, String number) throws ParseException {
		Map<String,Object> param=new HashMap<String,Object>();
		Map<String,Object> map=new HashMap<String,Object>();
		param.put("type", type);
		param.put("phoneNumber", phoneNumber);
		//登陆查找是否有这个用户 没有创建
		
		if(number==null){
			map.put("0", "请输入验证码");
			return map;
		}
		CheckNumber ch=wodeDao.findCheck(param);
		
		if(ch==null||!ch.getNumber().equals(number)){
			map.put("0", "错误");
			return map;
		}
		Long a=new Date().getTime()-new SimpleDateFormat("yyyyMMddHHmmss").parse(ch.getTime()).getTime();
		if(a/1000<=600){
			map.put("0", "成功");
			return map;
		}else{
			map.put("0", "过期");
			return map;
		}
	}
	//生成验证码 并发送
	public Map<String, Object> sendCheck(String phoneNumber, String type ) {
		Map<String,Object> map=new HashMap<String,Object>();
		String number=(int)(Math.random()*9000)+1000+"";
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("phoneNumber", phoneNumber);
		param.put("type", type);
		param.put("number", number);
		new YunTongXun().sendMessage(phoneNumber,number);
		wodeDao.insertDuanxin(param);
		wodeDao.deleteDuanxin();

		map.put("0", "成功");
		return map;
	}

	public Map<String, Object> ceshi() throws APIConnectionException, APIRequestException {
		Map<String, Object> map = new HashMap<String,Object>();

		new Push().push();
		map.put("0", "成功");
		return map;
	}
	public Map<String, Object> clickNotified(String id) {
		Map<String,Object> map=new HashMap<String,Object>();

		Notified notified=auntDao.findNotifiedById( id);
		if(notified.getState().equals("未读")){
			auntDao.updateNotifiedById(id);
			auntDao.updateUserNotifiedById(notified.getPhoneNumber());
			map.put("0", "成功");
		}else{
			map.put("0", "成功");
		}
		return map;
	}
	//余额支付
	public Map<String, Object> balancePaid(String orderNumber, String type,String redeemCode) {
		Map<String, Object> param = new HashMap<String,Object>();
		Map<String, Object> map = new HashMap<String,Object>();
		param.put("orderNumber", orderNumber);
		param.put("redeemCode", redeemCode);
		param.put("payType", "余额");

		map.put("0", "失败");
		if(type.equals("日常保洁")){
			ROrder r=orderDao.findROrder(orderNumber);
			UserInfo user=wodeDao.findUserByPhone(r.getPhoneNumber());
			//账户余额够
			if(user.getMemberBalance()>=r.getRealPrice()){
				//有优惠券 1减少订单价格 2删除优惠券
				if(!redeemCode.equals("")&&redeemCode!=null){
						Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
						param.put("discountAmount", cp.getDiscountAmount());
						yuyueDao.rbindCoupon(param);
						couponDao.deleteCoupon(redeemCode);
						r=orderDao.findROrder(orderNumber);

					}
				param.put("price", r.getRealPrice());
				String vip=wodeDao.findUserByPhone(r.getPhoneNumber()).getMemberLevel();
				if(vip.equals("VIP1")||vip.equals("VIP2")){
					param.put("price",(Float)param.get("price")*(0.75f));
				}else if(vip.equals("VIP3")||vip.equals("VIP4")){
					param.put("price",(Float)param.get("price")*(0.7f));
				}else if(vip.equals("VIP5")||vip.equals("VIP6")){
					param.put("price",(Float)param.get("price")*(0.65f));
				}
				param.put("phoneNumber", user.getPhoneNumber());
				wodeDao.updateMemberBalance(param);
				yuyueDao.rzhifu(param);
				yuyueDao.ryuezhifu(param);
				map.put("0", "成功");

			}
		}else if(type.equals("沙发护理")){
			SOrder r=orderDao.findSOrder(orderNumber);
			UserInfo user=wodeDao.findUserByPhone(r.getPhoneNumber());
			
			if(user.getMemberBalance()>=r.getRealPrice()){
				if(!redeemCode.equals("")&&redeemCode!=null){
					Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
					param.put("discountAmount", cp.getDiscountAmount());
					yuyueDao.sbindCoupon(param);
					couponDao.deleteCoupon(redeemCode);
					r=orderDao.findSOrder(orderNumber);
				}

				param.put("price", r.getRealPrice());
				param.put("phoneNumber", user.getPhoneNumber());
				wodeDao.updateMemberBalance(param);
				yuyueDao.szhifu(param);
				yuyueDao.syuezhifu(param);

				map.put("0", "成功");

			}
		}else if(type.equals("开荒保洁")){
			KOrder r=orderDao.findKOrder(orderNumber);
			UserInfo user=wodeDao.findUserByPhone(r.getPhoneNumber());
			if(user.getMemberBalance()>=r.getRealPrice()){
				if(!redeemCode.equals("")&&redeemCode!=null){
					Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
					param.put("discountAmount", cp.getDiscountAmount());
					yuyueDao.kbindCoupon(param);
					couponDao.deleteCoupon(redeemCode);
					r=orderDao.findKOrder(orderNumber);
				}
				param.put("price", r.getRealPrice());
				param.put("phoneNumber", user.getPhoneNumber());
				
				wodeDao.updateMemberBalance(param);
				yuyueDao.kzhifu(param);
				yuyueDao.kyuezhifu(param);

				map.put("0", "成功");

			}
		}else if (type.equals("家电清洗")){
			JOrder r=orderDao.findJOrder(orderNumber);
			UserInfo user=wodeDao.findUserByPhone(r.getPhoneNumber());
			if(user.getMemberBalance()>=r.getRealPrice()){
				if(!redeemCode.equals("")&&redeemCode!=null){
					Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
					param.put("discountAmount", cp.getDiscountAmount());
					yuyueDao.jbindCoupon(param);
					couponDao.deleteCoupon(redeemCode);
					r=orderDao.findJOrder(orderNumber);

				}
				param.put("price", r.getRealPrice());
				param.put("phoneNumber", user.getPhoneNumber());
				wodeDao.updateMemberBalance(param);
				yuyueDao.jzhifu(param);
				yuyueDao.jyuezhifu(param);

				map.put("0", "成功");

			}
		}else if(type.equals("地板护理")){
			DOrder r=orderDao.findDOrder(orderNumber);
			UserInfo user=wodeDao.findUserByPhone(r.getPhoneNumber());
			if(user.getMemberBalance()>=r.getRealPrice()){
				if(!redeemCode.equals("")&&redeemCode!=null){
					Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
					param.put("discountAmount", cp.getDiscountAmount());
					yuyueDao.dbindCoupon(param);
					couponDao.deleteCoupon(redeemCode);
					r=orderDao.findDOrder(orderNumber);

				}
				param.put("price", r.getRealPrice());
				param.put("phoneNumber", user.getPhoneNumber());
				wodeDao.updateMemberBalance(param);
				yuyueDao.dzhifu(param);
				yuyueDao.dyuezhifu(param);

				map.put("0", "成功");

			}
		}else if(type.equals("擦玻璃")){
			COrder r=orderDao.findCOrder(orderNumber);
			UserInfo user=wodeDao.findUserByPhone(r.getPhoneNumber());
			if(user.getMemberBalance()>=r.getRealPrice()){
				if(!redeemCode.equals("")&&redeemCode!=null){
					Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
					param.put("discountAmount", cp.getDiscountAmount());
					yuyueDao.cbindCoupon(param);
					couponDao.deleteCoupon(redeemCode);
					r=orderDao.findCOrder(orderNumber);

				}
				param.put("price", r.getRealPrice());
				param.put("phoneNumber", user.getPhoneNumber());
				wodeDao.updateMemberBalance(param);
				yuyueDao.czhifu(param);
				yuyueDao.cyuezhifu(param);

				map.put("0", "成功");

			}
		}
		
		return map;
	}
	public Map<String, Object> house() {
		Map<String,Object> map=new HashMap<String,Object>();
		List<Location> list=new ArrayList<Location>();
		list=wodeDao.findLocation();
		map.put("A", list);
		return map;
	}
	public List loca() {
		List<Location> list=new ArrayList<Location>();
		List listResult=new ArrayList();
		list=wodeDao.findLocation();
		for(Location loca:list){
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("CODE", loca.getLocation());
			map.put("NAME", loca.getLocation());
			listResult.add(map);
			
		}
		

		return listResult;
	}
	public List sType() {
		List listResult=new ArrayList();
		Map<String,Object> map1=new HashMap<String,Object>();
		map1.put("CODE", "日常保洁");
		map1.put("NAME", "日常保洁");
		listResult.add(map1);
		Map<String,Object> map2=new HashMap<String,Object>();
		map2.put("CODE", "沙发护理");
		map2.put("NAME", "沙发护理");
		listResult.add(map2);
		Map<String,Object> map3=new HashMap<String,Object>();
		map3.put("CODE", "开荒保洁");
		map3.put("NAME", "开荒保洁");
		listResult.add(map3);
		Map<String,Object> map4=new HashMap<String,Object>();
		map4.put("CODE", "家电清洗");
		map4.put("NAME", "家电清洗");
		listResult.add(map4);
		Map<String,Object> map5=new HashMap<String,Object>();
		map5.put("CODE", "地板护理");
		map5.put("NAME", "地板护理");
		listResult.add(map5);
		Map<String,Object> map6=new HashMap<String,Object>();
		map6.put("CODE", "擦玻璃");
		map6.put("NAME", "擦玻璃");
		listResult.add(map6);
		Map<String,Object> map7=new HashMap<String,Object>();
		map7.put("CODE", "周期订单(一周多次)");
		map7.put("NAME", "周期订单(一周多次)");
		listResult.add(map7);
		Map<String,Object> map8=new HashMap<String,Object>();
		map8.put("CODE", "周期订单(一周一次)");
		map8.put("NAME", "周期订单(一周一次)");
		listResult.add(map8);
		Map<String,Object> map9=new HashMap<String,Object>();
		map9.put("CODE", "周期订单(两周一次)");
		map9.put("NAME", "周期订单(两周一次)");
		listResult.add(map9);
		return listResult;
	}
	public Map<String, Object> registerCoupon(String phoneNumber) throws APIConnectionException, APIRequestException {
		Map<String,Object> map=new HashMap<String,Object>();
		Map<String,Object> param=new HashMap<String,Object>();
		String redeemCode=UUID.randomUUID().toString().substring(0, 8);
		param.put("redeemCode", redeemCode);
		param.put("discountAmount", "10");
		param.put("serviceType", "日常保洁");
		param.put("activationTime",new Date());
		param.put("phoneNumber",phoneNumber);

		Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.YEAR, 1);
		param.put("finallyTime",calendar.getTime());
		//赠送10优惠券
		wodeDao.sendCoupon(param);
		param.put("redeemCode", UUID.randomUUID().toString().substring(0, 8));
		wodeDao.sendCoupon(param);
		//发送短信
		String[] dat={"20"};
		new YunTongXun().register(phoneNumber,"86583",dat);
		map.put("A", "");
		return map;
	}
	public Map<String, Object> loginout(String phoneNumber) {
		Map<String,Object> map=new HashMap<String,Object>();
		Map<String,Object> param=new HashMap<String,Object>();
		String token=UUID.randomUUID().toString();
		param.put("phoneNumber", phoneNumber);
		param.put("token", token);
		wodeDao.resetToken(param);
		map.put("0", "成功");
		return map;
	}
	//删除原头像
	public void deleteHead(String phoneNumber,HttpSession session){
		UserInfo user=wodeDao.findUserByPhone(phoneNumber);
		if(user.getHeadPortrait().equals("")||user.getHeadPortrait().substring(user.getHeadPortrait().length()-1, user.getHeadPortrait().length()).equals("0")){
			
		}else{
			String after=user.getHeadPortrait().split("images/")[1];
//			session.getServletContext().getRealPath("images")  ROOT下的地址
			String begin = "C:\\Program Files\\Tomcat 7.0\\webapps\\cleaning\\images\\";// 储存地址+文件名 
			String path=begin+after;
			System.err.println("path"+path);
			 File targetFile = new File(path);
		        if(targetFile.exists()){
		        	targetFile.delete();
		        }
		}
		
	}
	
	public static List paixuAddress(List<Address> listall) throws ParseException{
		for (int i = 0; i < listall.size(); i++) {   
	       if (listall.get(i).getTag().equals("1")){
	    	   Address  temp = listall.get(i);   
		        listall.set(i,listall.get(0));   
		        listall.set(0,temp);
		        break;
	       }
	    }   
		return listall;
		
	}
	public synchronized void shibie() throws InterruptedException, AlipayApiException {
		AlipayClient alipayClient = new DefaultAlipayClient(MyParam.MYALIPAY_CLIENTADDRESS,MyParam.MYALIPAY_APPID, MyParam.MYALIPAY_APPPRIVATEKEY,"json","utf-8",MyParam.MYALIPAY_ALIPAYPUBLICKEY, "RSA2");
		ZhimaCustomerCertificationInitializeRequest request = new ZhimaCustomerCertificationInitializeRequest();
		request.setBizContent("{" +
		"    \"transaction_id\":\"ZGYD201610252323000001234\"," +
		"    \"product_code\":\"w1010100000000002978\"," +
		"    \"biz_code\":\"FACE\"," +
		"    \"identity_param\":\"{\\\"identity_type\\\":\\\"CERT_INFO\\\",\\\"cert_type\\\":\\\"IDENTITY_CARD\\\",\\\"cert_name\\\":\\\"收委\\\",\\\"cert_no\\\":\\\"260104197909275964\\\"}\"," +
		"    \"ext_biz_param\":\"{}\"" +
		"  }");
		ZhimaCustomerCertificationInitializeResponse response = alipayClient.execute(request);
		if(response.isSuccess()){
		System.out.println("调用成功");
		} else {
		System.out.println("调用失败");
		}
	}
	public String headTest(HttpServletRequest request,HttpSession session,String phoneNumber) {
		
		return  MyUtil.headImage(request, session, phoneNumber);
	}
	//签到表里的积分提到用户表里面
public  void exchangeCredits(String phoneNumber) {
	Map<String,Object> param=new HashMap<String,Object>();
		SignIn sign=wodeDao.findSignByPhone(phoneNumber);
		param.put("credits", sign.getCredits());
		param.put("phoneNumber", phoneNumber);
		wodeDao.updateCreditsHouTai(param);
	}
//签到表里的积分提到用户表里面 相反
public  void exchangeCreditsHouTai(String phoneNumber) {
	System.err.println("phoneNumber"+phoneNumber);
Map<String,Object> param=new HashMap<String,Object>();
	SignIn sign=wodeDao.findSignByPhone(phoneNumber);
	if(sign==null){
		wodeDao.createSign(phoneNumber);
	}
	UserInfo user=wodeDao.findUserByPhone(phoneNumber);
	param.put("credits",user.getPoints());
	param.put("phoneNumber", phoneNumber);
	wodeDao.updateCredits(param);
}
	

	
	 
	
	
	
}
